import { fetchOriginCurrencylist } from '@/service/currencylist';
import { Currency } from '@/types/currency';

/**
 * 货币信息
 *
 * 因为这个数据不涉及视图更新,只是做数据处理用
 * 所以做了一个简单的实体类
 */

class CurrencyList {
  private currencyList: Currency[] = [];
  private currencyMap = new Map<string, Currency>();

  async fetchData() {
    const res = await fetchOriginCurrencylist();
    if (res && res.data && res.data.code === 0) {
      this.currencyList = res.data.result.currency;
      this.currencyMap = new Map<string, Currency>(
        res.data.result.currency.map((c) => {
          return [c.name, c];
        }),
      );
    } else {
    }
  }

  async getCurrencyList(): Promise<Currency[]> {
    return new Promise(async (resolve) => {
      if (this.currencyList.length === 0) {
        await this.fetchData();
      }
      resolve(this.currencyList);
    });
  }

  async getCurrencyMap(): Promise<Map<string, Currency>> {
    return new Promise(async (resolve) => {
      if (this.currencyList.length === 0) {
        await this.fetchData();
      }
      resolve(this.currencyMap);
    });
  }
}

const currencyListModel = new CurrencyList();

export default currencyListModel;
